package raone;

import java.io.*;
import java.net.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;

public class Server_T_2 {
	public static int [] Thread_result = {0,0};
	public static int estblish_write(String x) throws IOException
	{
	int fail=0;
	FileWriter fw;
	fw = new FileWriter("Log.txt");
	String temp = x;
	temp = "Connection Established with :" + temp;
	fw.write(temp + System.getProperty( "line.separator" ));
	fw.close();
	return fail;
		
	}
	public static int fail_write(String x) throws IOException
	{
	int fail=0;
	FileWriter fw;
	fw = new FileWriter("Log.txt",true);
	String temp = x;
	temp = "\nConnection Failed with :" + temp;
	fw.write(temp + System.getProperty( "line.separator" ));
	fw.close();
	return fail;
		
	}
	public static void Print_Results(String[] Address_list) throws IOException
	{
		for (int i=0;i<2;i++)
		{
			//System.out.println("In Print Results");
			if(Server_T.Thread_result[i]==0)
				estblish_write(Address_list[i]);
			else
				fail_write(Address_list[i]);
		}		
	}
	
  
	public static void main(String[] args)throws Exception
	{
		String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
	    Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);		    
		FileWriter fw;
		fw = new FileWriter("Log.txt");
		fw.write(System.getProperty( "line.separator" ) + "----------------------"+ System.getProperty( "line.separator" ));
		fw.write(sdf.format(cal.getTime())+ " | Started" + System.getProperty( "line.separator" ));
		fw.close();
		System.out.println("Server Started");
		
		ServerSocket ServerSocket= new ServerSocket(7780);
		ServerSocket.setSoTimeout(10000);
		Socket[] Clients;        
		String[] Address_list;
		Address_list = new String[2];
        Clients = new Socket[2];
        MyThread[] Threads;
        Threads = new MyThread[2];
        
        for(int i=0;i<2;i++)
	    {
	    	try{
        	//System.out.println( "Number" + i);
        	Clients[i] = ServerSocket.accept();
        	//Clients[i].setSoTimeout(6*1000);
        	String tname = Integer.toString(i);
	    	Threads[i] = new MyThread(Clients[i],i,tname);
	    	Address_list[i] = Clients[i].getInetAddress().getHostAddress();
	    	}
	    	catch(SocketTimeoutException s)
			{
			continue;	
			}
        }
        Threads[0].t.join();
    	Threads[1].t.join();
    	try{}
		finally
			{
			ServerSocket.close();
			System.out.println("Printing Log");
			//Print_Results(Address_list);
			}
	}
	
		
	}
	
	
	
	
	
	

